package com.redhipps.hips.client.model;

import java.util.List;
import java.util.Map;

import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONBoolean;
import com.google.gwt.json.client.JSONNull;
import com.google.gwt.json.client.JSONNumber;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.json.client.JSONValue;

public class Converters {

  public static JSONValue valueForObject(Object o) {
    if (o == null) {
      return JSONNull.getInstance();
    }
    if (o instanceof String) {
      return new JSONString((String) o);
    }
    if (o instanceof Number) {
      return new JSONNumber(((Number) o).doubleValue());
    }
    if (o instanceof Boolean) {
      return JSONBoolean.getInstance(((Boolean) o).booleanValue());
    }
    if (o instanceof List<?>) {
      return valueForList((List<?>) o);
    }
    // if (o.getClass().isArray()) {
    //   return valueForArray((Object[]) o);
    // }
    throw new IllegalArgumentException("Unsupported object type in conversion: " + o);
  }

  public static JSONArray valueForArray(Object[] o) {
    JSONArray array = new JSONArray();
    int i = 0;
    for (Object object : o) {
      array.set(i, valueForObject(object));
      i += 1;
    }
    return array;
  }

  public static JSONArray valueForList(List<?> list) {
    JSONArray array = new JSONArray();
    int i = 0;
    for (Object object : list) {
      array.set(i, valueForObject(object));
      i += 1;
    }
    return array;
  }

  public static JSONObject valueForMap(Map<String, Object> map) {
    JSONObject o = new JSONObject();
    for (Map.Entry<String, Object> e : map.entrySet()) {
      o.put(e.getKey(), valueForObject(e.getValue()));
    }
    return o;
  }

  private Converters() {}
}
